package scatter.wxcp.rest.notify;

import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import scatter.common.rest.notify.NotifyParam;
import scatter.common.rest.tools.SpringContextHolder;
import scatter.wxcp.rest.config.WxCpProperties;

import java.util.Map;

/**
 * <p>
 * 默认企业微信 agencyId 实现
 * 可被覆盖
 * </p>
 *
 * @author yangwei
 * @since 2021-08-25 19:41
 */
@ConfigurationProperties(prefix = "scatter.notify.resolver.wxcp")
public class DefaultWxCpNotifyAgencyIdResolverImpl implements IWxCpNotifyAgencyIdResolver{

	/**
	 * key 为按 business
	 */
	@Setter
	private Map<String,Integer> agencyIdMap;

	@Override
	public Integer resolve(NotifyParam param) {
		Integer agencyId = getAgencyIdByConfig(param);
		if (agencyId != null) {
			return agencyId;
		}

		// 如果配置只有一个，那么就取这个
		WxCpProperties bean = SpringContextHolder.getBean(WxCpProperties.class);
		if (bean.getAppConfigs().size() == 1) {
			return bean.getAppConfigs().get(0).getAgentId();
		}
		return null;
	}

	/**
	 * 根据配置获取
	 * @param param
	 * @return
	 */
	protected Integer getAgencyIdByConfig(NotifyParam param){
		Integer result = null;
		if (agencyIdMap == null) {
			return result;
		}
		/**
		 * 根据category
		 */
		if (param.getCategory() != null) {
			result = agencyIdMap.get(param.getCategory());
			if (result != null) {
				return result;
			}
		}
		if (param.getContentType() != null) {
			/**
			 * 根据contentType
			 */
			result = agencyIdMap.get(param.getContentType());
			if (result != null) {
				return result;
			}
		}
		if (param.getCategory() != null && param.getContentType() != null) {
			/**
			 * 根据contentType
			 */
			result = agencyIdMap.get(param.getCategory() + "." + param.getContentType());
			if (result != null) {
				return result;
			}
		}
		// 没有找到直接返回
		return result;
	}
}
